package com.ecarx.engineermode.tab.adapter;

import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;

import com.ecarx.engineermode.R;
import com.ecarx.engineermode.tab.model.ChildItem;
import com.ecarx.engineermode.tab.model.GroupItem;
import com.ecarx.engineermode.tab.model.TabItem;

import java.util.List;

public class ExpandableListviewAdapter extends BaseExpandableListAdapter {
    //Model：定义的数据
    private final List<TabItem> tabItemList;
    private final Context context;

    private static final String TAG = "ExpandableListviewAdapt";


    private static final ColorStateList COLOR_DEF = ColorStateList.valueOf(Color.parseColor("#323232"));
    private static final ColorStateList COLOR_SELECT = ColorStateList.valueOf(Color.BLUE);

    public ExpandableListviewAdapter(Context context, List<TabItem> tabItemList) {
        this.context = context;
        this.tabItemList = tabItemList;
    }

    @Override
    public int getGroupCount() {
        return tabItemList.size();
    }

    @Override
    public int getChildrenCount(int i) {
        return tabItemList.get(i).getChildItemList().size();
    }

    @Override
    public Object getGroup(int i) {
        return tabItemList.get(i);
    }

    @Override
    public Object getChild(int i, int i1) {
        return tabItemList.get(i).getChildItemList().get(i1);
    }

    @Override
    public long getGroupId(int i) {
        return i;
    }

    @Override
    public long getChildId(int i, int i1) {
        return i1;
    }

    @Override
    //分组和子选项是否持有稳定的ID, 就是说底层数据的改变会不会影响到它们
    public boolean hasStableIds() {
        return false;
    }

    /**
     * 获取显示指定组的视图对象
     *
     * @param groupPosition 组位置
     * @param isExpanded    该组是展开状态还是伸缩状态，true=展开
     * @param convertView   重用已有的视图对象
     * @param parent        返回的视图对象始终依附于的视图组
     */
    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        GroupViewHolder groupViewHolder;
        ExpandableListView expandableListView = (ExpandableListView) parent;
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.tab_item, parent, false);
            groupViewHolder = new GroupViewHolder();
            groupViewHolder.tvName = convertView.findViewById(R.id.tv_item_name);
            groupViewHolder.ivArrow = convertView.findViewById(R.id.iv_item_arrow);
            groupViewHolder.root = convertView.findViewById(R.id.cl_tab_item_root);
            groupViewHolder.ivIcon = convertView.findViewById(R.id.iv_item_icon);
            groupViewHolder.ivIconBlue = convertView.findViewById(R.id.iv_item_icon_blue);
            convertView.setTag(groupViewHolder);
        } else {
            groupViewHolder = (GroupViewHolder) convertView.getTag();
        }
        TabItem tabItem = tabItemList.get(groupPosition);
        GroupItem groupItem = tabItem.getGroupItem();
        String itemName = groupItem.getItemName();
        groupViewHolder.tvName.setText(itemName);
        groupViewHolder.ivIcon.setImageDrawable(tabItem.getGroupItem().getIcon());
        groupViewHolder.ivIconBlue.setImageDrawable(tabItem.getGroupItem().getSubIcon());
        groupViewHolder.ivArrow.setVisibility(tabItem.isOnlyGroup() ? View.GONE : View.VISIBLE);
        //如果是展开状态，
        if (isExpanded) {

            groupViewHolder.ivArrow.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_arrow_down));
        } else {
            groupViewHolder.ivArrow.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_arrow_right));
        }
        switchSelectedView(expandableListView, cacheSelectedGroupPositionName, cacheSelectedChildPositionName, cacheOnlyGroup);
        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        ChildViewHolder childViewHolder;
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.tab_item_chlid, parent, false);
            childViewHolder = new ChildViewHolder();
            childViewHolder.tvName = convertView.findViewById(R.id.tv_item_name);
            childViewHolder.root = convertView.findViewById(R.id.cl_tab_item_child_root);
            convertView.setTag(childViewHolder);

        } else {
            childViewHolder = (ChildViewHolder) convertView.getTag();
        }
        ChildItem childItem = tabItemList.get(groupPosition).getChildItemList().get(childPosition);
        childViewHolder.tvName.setText(childItem.getItemName());
        switchSelectedView((ExpandableListView) parent, cacheSelectedGroupPositionName, cacheSelectedChildPositionName, cacheOnlyGroup);
        return convertView;
    }

    String cacheSelectedGroupPositionName = "";
    String cacheSelectedChildPositionName = "";
    boolean cacheOnlyGroup = false;

    private void switchSelectedViewDelayed(ExpandableListView viewGroup, String selectedGroupPositionName, String selectedChildPositionName, boolean isOnlyGroup) {

        if (isOnlyGroup || !TextUtils.isEmpty(selectedChildPositionName)) {
            //触发仅一级菜单，和二级菜单事件时，保存此次点击名称
            cacheSelectedGroupPositionName = selectedGroupPositionName;
            cacheSelectedChildPositionName = selectedChildPositionName;
        }
        String groupName = cacheSelectedGroupPositionName;
        String childName = cacheSelectedChildPositionName;

        cacheOnlyGroup = isOnlyGroup;

        int groupCount = viewGroup.getChildCount();


        for (int i = 0; i < groupCount; i++) {
            ViewGroup groupItem = (ViewGroup) viewGroup.getChildAt(i);

            //从viewTag中取出文字名称进行匹配，对应上的就要变蓝色
            ChildViewHolder tag = (ChildViewHolder) groupItem.getTag();
            String tagName = tag.tvName.getText().toString();
            boolean isSelected = groupName.equals(tagName) || childName.equals(tagName);


            ColorStateList textColors = tag.tvName.getTextColors();
            if ((!isSelected || textColors != COLOR_SELECT) && (isSelected || textColors != COLOR_DEF)) {
                tag.tvName.setTextColor(isSelected ? COLOR_SELECT : COLOR_DEF);
                if (tag instanceof GroupViewHolder) {
                    GroupViewHolder groupViewHolder = (GroupViewHolder) tag;
                    groupViewHolder.ivArrow.setImageTintList(isSelected ? COLOR_SELECT : COLOR_DEF);
                    groupViewHolder.ivArrow.setImageTintMode(PorterDuff.Mode.SRC_IN);
                    groupViewHolder.ivIcon.setVisibility(!isSelected ? View.VISIBLE : View.INVISIBLE);
                    groupViewHolder.ivIconBlue.setVisibility(isSelected ? View.VISIBLE : View.INVISIBLE);

                }
            }

        }
    }


    /**
     * 滑动和点击目录都需要更新和检查一遍列表的颜色，
     */
    public void switchSelectedView(ExpandableListView viewGroup, String selectedGroupPositionName, String selectedChildPositionName, boolean isOnlyGroup) {
        viewGroup.postDelayed(new Runnable() {
            @Override
            public void run() {
                switchSelectedViewDelayed(viewGroup, selectedGroupPositionName, selectedChildPositionName, isOnlyGroup);
            }
        }, 50);
    }

    //指定位置上的子元素是否可选中
    @Override
    public boolean isChildSelectable(int i, int i1) {
        return true;
    }

    static class ChildViewHolder {
        TextView tvName;
        ConstraintLayout root;
    }

    static class GroupViewHolder extends ChildViewHolder {
        ImageView ivArrow;
        ImageView ivIcon;
        ImageView ivIconBlue;
    }
}